package com.ye.media;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import com.ye.media.R;
import com.ye.media.music.MusicListAdapter;
import com.ye.media.util.TimeConvert;

import android.util.Log;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.SeekBar;
import android.media.MediaPlayer;
import android.net.Uri;

public class MainActivity extends Activity  implements SeekBar.OnSeekBarChangeListener{
    private final String TAG = "MainActivity";
	private ImageButton btnPrev;
	private ImageButton btnPlay;
	private ImageButton btnNext;
	private ListView listMusic;
	private TextView textTime;
	private TextView textCurrent;
	private SeekBar seekPlay;
	private ImageView albumImg;
	private int     nAudioLen;
	volatile private int     nCurrentPos;
	
	private AudioManager audioManager;
	private MediaPlayer mediaPlayer;
	
	volatile private boolean isSeekBarTouching = false; 
	
	private Handler mHandler;
	private UpThread mUpThread;
	private Timer timer;
	
    private static final String strExternalMediaUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString();
    private static final Uri uriArtwork = Uri.parse("content://media/external/audio/albumart");
	protected static final int RIGHT = 0;
	protected static final int LEFT = 1;
    private GestureDetector gestureDetector;
    
    //音乐列表
    private int[] _ids;// 保存音乐ID临时数组  
    private String[] _artists;// 保存艺术家  
    private String[] _titles;// 标题临时数组  
    private ListView listView;// 列表对象  
    private Cursor cursor;  
    private MusicListAdapter musicListAdapter;  
    private AlertDialog ad = null;  
    private AlertDialog.Builder builder = null;  
    private static final String MUSIC_LIST = "com.android.musicplayer.activity.list";  
    /**  
     * 定义查找音乐信息数组，1.标题 2.音乐时间 3.艺术家 4.音乐id 5.显示名字 6.数据  
     */  
    String[] media_music_info = new String[] { MediaStore.Audio.Media.TITLE,  
            MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ARTIST,  
            MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME,  
            MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ALBUM_ID };
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
        listView = (ListView) findViewById(R.layout.musicList);  
        listView.setOnItemClickListener(new MusicListOnClickListener());// 创建一个ListView监听器对象  
        showMusicList();
        
		//触控事件
		gestureDetector = new GestureDetector(MainActivity.this,onGestureListener);
		
		//打开音乐
		mediaPlayer = new MediaPlayer();
    	try {
    		File file = new File(Environment.getExternalStorageDirectory(), "OneLove.mp3");
			mediaPlayer.setDataSource(file.getPath());
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
      	mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
			mediaPlayer.prepare();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
		
		textTime = (TextView)findViewById(R.id.playTime);
		textCurrent = (TextView)findViewById(R.id.textCurrent);
		btnPlay=(ImageButton)findViewById(R.id.btnPlay);
		btnPlay.setOnClickListener(new OnClickListener() {  
            @Override 
            public void onClick(View v) {
            	nAudioLen = mediaPlayer.getDuration();
            	textTime.setText(TimeConvert.formatTime(nAudioLen));
            	if(mediaPlayer.isPlaying()){
            		btnPlay.setImageResource(R.drawable.btn_play);
            		mediaPlayer.pause();
            	}else{
            		btnPlay.setImageResource(R.drawable.btn_pause);
            		seekPlay.setMax(nAudioLen);
            		mediaPlayer.start();
            	}
            }
        }); 
		
		seekPlay = (SeekBar)findViewById(R.id.playProgress);
		seekPlay.setOnSeekBarChangeListener(this);
		mUpThread = new UpThread();
		mUpThread.start();
		
        //监听播放时回调函数  
        timer = new Timer();  
        timer.schedule(new TimerTask() {  
            @Override  
            public void run() {
                if(!isSeekBarTouching){  
                	int nPos = mediaPlayer.getCurrentPosition();
                	//不允许在主线程中操作更新控件
                	//textCurrent.setText(TimeConvert.formatTime(nPos));
                    seekPlay.setProgress(nPos);  
                }  
            }  
        },0,50);  
        
        //接收线程中发来的位置信息更新当前播放时间
		mHandler = new Handler() {
	        @Override    
	        public void handleMessage(Message msg) {    
	            super.handleMessage(msg);    
	            switch (msg.what) {    
	            case 1:
	                //Log.i(TAG, "handleMessage msg.obj = " + (String)msg.obj);
	                int nPos = msg.arg1;
	                textCurrent.setText(TimeConvert.formatTime(nPos));
	                break;    
	            default:    
	                break;    
	            }    
	        }
	    
	    };
	}

	
    private void showMusicList() {  
        cursor = getContentResolver().query(  
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, media_music_info,  
                null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);  
        cursor.moveToFirst();// 将游标移动到初始位置  
        _ids = new int[cursor.getCount()];// 返回int的一个列  
        _artists = new String[cursor.getCount()];// 返回String的一个列  
        _titles = new String[cursor.getCount()];// 返回String的一个列  
        for (int i = 0; i < cursor.getCount(); i++) {  
            _ids[i] = cursor.getInt(3);  
            _titles[i] = cursor.getString(0);  
            _artists[i] = cursor.getString(2);  
            cursor.moveToNext();// 将游标移到下一行  
        }  
        musicListAdapter = new MusicListAdapter(this, cursor);  
        listView.setAdapter(musicListAdapter);// 用setAdapter装载数据  
        listView.setOnCreateContextMenuListener(new ContextMenuListener());  
    } 
    
    public boolean onKeyDown(int keyCode, KeyEvent event) {  
        if (keyCode == KeyEvent.KEYCODE_BACK) {  
            if (scanSdReceiver != null)  
                unregisterReceiver(scanSdReceiver);  
            Intent intent = new Intent();  
            intent.setClass(this, MainActivity.class);  
            startActivity(intent);  
            finish();  
        }  
        return true;  
    }  
    
	public class UpThread extends Thread{
	    @Override
	    public void run() {
	        super.run();
	        //进行耗时操作
	        while(true){
	        	try {
	        		Thread.sleep(50);
	        	} catch (InterruptedException e) {
	        		e.printStackTrace();
	        	}
	        	Message msg = new Message();
	        	msg.what = 1;
	        	msg.arg1 = mediaPlayer.getCurrentPosition();
	        	//Log.i(TAG, "sendMessage msg.obj = " + (String)msg.obj);
	        	mHandler.sendMessage(msg);//handler发送消息
	        }
	    }
	}


	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
		if(fromUser&&(progress == seekBar.getMax())){
			
		}
	}


	@Override
	public void onStartTrackingTouch(SeekBar arg0) {
		isSeekBarTouching = true;
	}


	@Override
	public void onStopTrackingTouch(SeekBar arg0) {
		isSeekBarTouching = false;
		mediaPlayer.seekTo(arg0.getProgress());
	}
	

    private GestureDetector.OnGestureListener onGestureListener =   
            new GestureDetector.SimpleOnGestureListener() {  
            @Override  
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,  
                    float velocityY) {  
                float x = e2.getX() - e1.getX();  
                float y = e2.getY() - e1.getY();  
      
                if (x > 0) {  
                    doResult(RIGHT);  
                } else if (x < 0) {  
                    doResult(LEFT);  
                }  
                return true;  
            }  
        };  
      
        public boolean onTouchEvent(MotionEvent event) {  
            return gestureDetector.onTouchEvent(event);  
        }  
      
        public void doResult(int action) {  
      
            switch (action) {  
            case RIGHT:  
            	setContentView(R.layout.activity_main);
                break;
            case LEFT:  
            	setContentView(R.layout.music_list);  
                break;  
      
            }  
        }  
}
